<template>
  <div class="admin-payment">
    <div class="page-header">
      <h1>缴费管理</h1>
      <p>管理学生缴费记录和确认</p>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="院校">
          <el-select v-model="searchForm.schoolId" placeholder="选择院校" clearable>
            <el-option v-for="school in schools" :key="school.id" :label="school.name" :value="school.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费类型">
          <el-select v-model="searchForm.paymentType" placeholder="缴费类型" clearable>
            <el-option label="校测费" value="exam" />
            <el-option label="学费" value="tuition" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select v-model="searchForm.paymentStatus" placeholder="支付状态" clearable>
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已退费" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="姓名/身份证" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadPayments">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>缴费记录</span>
          <div>
            <el-button type="warning" @click="loadUnpaidStudents">未缴费名单</el-button>
            <el-button type="success" @click="exportData">导出数据</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="payments" stripe>
        <el-table-column prop="studentName" label="学生姓名" />
        <el-table-column prop="idCard" label="身份证号" />
        <el-table-column prop="paymentType" label="缴费类型">
          <template #default="{ row }">
            <el-tag :type="row.paymentType === 'exam' ? 'primary' : 'success'">
              {{ row.paymentType === 'exam' ? '校测费' : '学费' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额">
          <template #default="{ row }">
            ¥{{ row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" />
        <el-table-column prop="paymentStatus" label="支付状态">
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusType(row.paymentStatus)">
              {{ getPaymentStatusText(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentTime" label="支付时间" />
        <el-table-column prop="transactionId" label="交易流水号" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">查看</el-button>
            <el-button 
              v-if="row.paymentStatus === 'pending'" 
              size="small" 
              type="primary" 
              @click="confirmPayment(row)"
            >
              确认缴费
            </el-button>
            <el-button 
              v-if="row.paymentStatus === 'paid'" 
              size="small" 
              type="danger" 
              @click="refundPayment(row)"
            >
              申请退费
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadPayments"
          @current-change="loadPayments"
        />
      </div>
    </el-card>

    <!-- 确认缴费对话框 -->
    <el-dialog v-model="confirmDialogVisible" title="确认缴费" width="500px">
      <el-form :model="confirmForm" label-width="120px">
        <el-form-item label="学生姓名">
          <span>{{ confirmForm.studentName }}</span>
        </el-form-item>
        <el-form-item label="缴费金额">
          <span>¥{{ confirmForm.amount }}</span>
        </el-form-item>
        <el-form-item label="交易流水号" required>
          <el-input v-model="confirmForm.transactionId" placeholder="请输入交易流水号" />
        </el-form-item>
        <el-form-item label="缴费凭证">
          <el-input v-model="confirmForm.receiptUrl" placeholder="请输入凭证URL（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitConfirm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 退费申请对话框 -->
    <el-dialog v-model="refundDialogVisible" title="申请退费" width="500px">
      <el-form :model="refundForm" label-width="120px">
        <el-form-item label="学生姓名">
          <span>{{ refundForm.studentName }}</span>
        </el-form-item>
        <el-form-item label="原缴费金额">
          <span>¥{{ refundForm.originalAmount }}</span>
        </el-form-item>
        <el-form-item label="退费金额" required>
          <el-input-number 
            v-model="refundForm.refundAmount" 
            :min="0" 
            :max="refundForm.originalAmount"
            :precision="2"
          />
        </el-form-item>
        <el-form-item label="退费原因" required>
          <el-input v-model="refundForm.reason" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRefund">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'

// 响应式数据
const loading = ref(false)
const payments = ref([])
const schools = ref([])

const searchForm = reactive({
  schoolId: '',
  paymentType: '',
  paymentStatus: '',
  keyword: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const confirmDialogVisible = ref(false)
const confirmForm = reactive({
  id: null,
  studentName: '',
  amount: 0,
  transactionId: '',
  receiptUrl: ''
})

const refundDialogVisible = ref(false)
const refundForm = reactive({
  id: null,
  studentName: '',
  originalAmount: 0,
  refundAmount: 0,
  reason: ''
})

// 方法
const loadPayments = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    const { data } = await api.get('/payment', { params })
    payments.value = data.records || []
    pagination.total = data.total || 0
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const loadSchools = async () => {
  try {
    const { data } = await api.get('/schools')
    schools.value = data.records || []
  } catch (error) {
    console.error('加载院校失败:', error)
  }
}

const resetSearch = () => {
  Object.assign(searchForm, {
    schoolId: '',
    paymentType: '',
    paymentStatus: '',
    keyword: ''
  })
  loadPayments()
}

const viewDetail = (row) => {
  ElMessage.info('查看详情功能待实现')
}

const confirmPayment = (row) => {
  Object.assign(confirmForm, {
    id: row.id,
    studentName: row.studentName,
    amount: row.amount,
    transactionId: '',
    receiptUrl: ''
  })
  confirmDialogVisible.value = true
}

const submitConfirm = async () => {
  if (!confirmForm.transactionId) {
    ElMessage.warning('请输入交易流水号')
    return
  }
  
  try {
    await api.put(`/payment/${confirmForm.id}/confirm`, null, {
      params: {
        transactionId: confirmForm.transactionId,
        receiptUrl: confirmForm.receiptUrl
      }
    })
    ElMessage.success('缴费确认成功')
    confirmDialogVisible.value = false
    loadPayments()
  } catch (error) {
    ElMessage.error('缴费确认失败')
  }
}

const refundPayment = (row) => {
  Object.assign(refundForm, {
    id: row.id,
    studentName: row.studentName,
    originalAmount: row.amount,
    refundAmount: row.amount,
    reason: ''
  })
  refundDialogVisible.value = true
}

const submitRefund = async () => {
  if (!refundForm.reason) {
    ElMessage.warning('请输入退费原因')
    return
  }
  
  try {
    await api.put(`/payment/${refundForm.id}/refund/apply`, null, {
      params: {
        refundAmount: refundForm.refundAmount,
        reason: refundForm.reason
      }
    })
    ElMessage.success('退费申请提交成功')
    refundDialogVisible.value = false
    loadPayments()
  } catch (error) {
    ElMessage.error('退费申请失败')
  }
}

const loadUnpaidStudents = async () => {
  try {
    const { data } = await api.get('/payment/unpaid')
    ElMessage.success(`共有 ${data.length} 名学生未缴费`)
  } catch (error) {
    ElMessage.error('查询失败')
  }
}

const exportData = () => {
  ElMessage.info('导出功能待实现')
}

const getPaymentStatusType = (status) => {
  const map = {
    pending: 'warning',
    paid: 'success',
    refunded: 'info'
  }
  return map[status] || 'info'
}

const getPaymentStatusText = (status) => {
  const map = {
    pending: '待支付',
    paid: '已支付',
    refunded: '已退费'
  }
  return map[status] || status
}

// 初始化
onMounted(() => {
  loadPayments()
  loadSchools()
})
</script>

<style lang="scss" scoped>
.admin-payment {
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 8px 0;
      font-size: 24px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #909399;
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style>